/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package interfaz;

import admin.Admin;
import admin.AdminSesion;
import controladores.Constantes;
import controladores.ControladorSocios;
import dialogos.InicioSesion;
import entidades.Sesion;
import interfaces.controlestablas.ControlSocios;
import interfaz.panelesinternos.FrameTablaGenerica;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import utiles.GrabarException;
import utiles.HttpHelper;
import utiles.UtilesCalendar;

/**
 *
 * @author Felipe
 */
public class Principal extends javax.swing.JFrame
{
    private Thread verificadorNotas;
    
    /**
     * Creates new form Principal
     */
    public Principal()
    {
        initComponents();
        setUp();
        
        this.addWindowListener(new WindowAdapter()
        {
            @Override
            public void windowClosing(WindowEvent e)
            {
                super.windowClosing(e);
                
                try
                {
                    Admin.getInstance().getAdminSesion().cerrarSesion(false);
                }
                catch (Exception ex)
                {
                    GrabarException.grabarExcepcion(ex);
                }
            }
        });
    }
    
    private void setUp ()
    {
        Sesion sesion = Admin.getInstance().getAdminSesion().getSesion();
        if (sesion != null)
        {
            labelSesion.setText("Sesión iniciada como " + sesion.getUsuario().getNombre() + " " + sesion.getUsuario().getApellido() + " - " + UtilesCalendar.getStringCompleto(sesion.getInicio()));
            
            //VerificadorNotasEntrada ver = new VerificadorNotasEntrada(sesion.getUsuario());
            //ver.agregarListener(new ListenerNuevaNotaEntrada(labelNotas));
            
            //verificadorNotas = new Thread (ver);
            //verificadorNotas.start();
        }
        else
            labelSesion.setText("Sesión no iniciada.");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {

        jToolBar1 = new javax.swing.JToolBar();
        botonSesion = new javax.swing.JButton();
        botonSocios = new javax.swing.JButton();
        filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0));
        escritorio = new javax.swing.JDesktopPane();
        jPanel1 = new javax.swing.JPanel();
        labelSesion = new javax.swing.JLabel();
        labelNotas = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Club Universitario Puerto Madryn");

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        botonSesion.setIcon(new javax.swing.ImageIcon("/home/fcarou/Dropbox/Programas/Club Universitario/Codigo/Club Universitario/iconos/sesion2.png")); // NOI18N
        botonSesion.setText("Sesión");
        botonSesion.setFocusable(false);
        botonSesion.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        botonSesion.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        botonSesion.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                botonSesionActionPerformed(evt);
            }
        });
        jToolBar1.add(botonSesion);

        botonSocios.setIcon(new javax.swing.ImageIcon("/home/fcarou/Dropbox/Programas/Club Universitario/Codigo/Club Universitario/iconos/clientes.png")); // NOI18N
        botonSocios.setText("Socios");
        botonSocios.setToolTipText("Ver, editar, agregar o eliminar socios al sistema");
        botonSocios.setFocusable(false);
        botonSocios.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        botonSocios.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        botonSocios.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                botonSociosActionPerformed(evt);
            }
        });
        jToolBar1.add(botonSocios);
        jToolBar1.add(filler1);

        javax.swing.GroupLayout escritorioLayout = new javax.swing.GroupLayout(escritorio);
        escritorio.setLayout(escritorioLayout);
        escritorioLayout.setHorizontalGroup(
            escritorioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        escritorioLayout.setVerticalGroup(
            escritorioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 418, Short.MAX_VALUE)
        );

        labelSesion.setText("Sesión iniciada como Felipe Carou - 19/19/19 - 14:14");

        labelNotas.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        labelNotas.setText("jLabel1");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelSesion)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 215, Short.MAX_VALUE)
                .addComponent(labelNotas, javax.swing.GroupLayout.PREFERRED_SIZE, 362, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelSesion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(labelNotas))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(escritorio, javax.swing.GroupLayout.Alignment.TRAILING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(escritorio)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botonSociosActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_botonSociosActionPerformed
    {//GEN-HEADEREND:event_botonSociosActionPerformed
        abrirPanelInterno (new FrameTablaGenerica(new ControlSocios()), 100, 100, 750, 600);
    }//GEN-LAST:event_botonSociosActionPerformed

    private void botonSesionActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_botonSesionActionPerformed
    {//GEN-HEADEREND:event_botonSesionActionPerformed
        AdminSesion control = Admin.getInstance().getAdminSesion();
        
        if (control.sesionIniciada())
        {
            if (JOptionPane.showConfirmDialog(JOptionPane.getFrameForComponent(this), "Seguro quiere cerrar sesion?\nSe perderán todos los datos que no hayan sido guardados.", "Sesión", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION)
            {
                if (control.cerrarSesion(true))
                {
                    setBotones (false);
                    control.eliminarDatosUsuario();
                }
                else
                {
                    JOptionPane.showMessageDialog(null, "Falló el cierre de sesión.");
                }
            }
        }
        else
        {            
            InicioSesion inicio = new InicioSesion(JOptionPane.getFrameForComponent(this), true);
            inicio.setLocationRelativeTo(null);
            inicio.setVisible(true);
            
            if (control.sesionIniciada())
            {
                setBotones(true);
            }
        }
    }//GEN-LAST:event_botonSesionActionPerformed

    private void setBotones (boolean set)
    {
        botonSocios.setEnabled(set);
    }
    
    private void abrirPanelInterno (JInternalFrame frame, int x, int y, int ancho, int alto)
    {
        frame.setLocation(x, y);
        frame.setSize(ancho, alto);
        escritorio.add(frame);
        frame.setVisible(true);
        frame.setClosable(true);
        frame.setIconifiable(true);
        frame.setResizable(true);
    }
    
    public static void main (String args[])
    {
        try
        {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
            {
                if ("Nimbus".equals(info.getName()))
                {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }
        catch (Exception e)
        {
            
        }
        
        ControladorSocios con = new ControladorSocios();
        if (con.getSocios().isEmpty())
        {
            HttpHelper helper = new HttpHelper(Constantes.URL_COMPLETA);
            System.out.println("Respuesta: " + helper.doGet("pruebas/inventar", null, null));
        }
        
        Principal p = new Principal();
        
        AdminSesion admin = Admin.getInstance().getAdminSesion();
        
        if (!admin.sesionIniciada())
        {
            InicioSesion inicio = new InicioSesion(p, true);
            inicio.setLocationRelativeTo(null);
            inicio.setVisible(true);
            
            if (!admin.sesionIniciada())
            {
                System.out.println("No hay sesion!");
                System.exit(0);
            }
        }
        
        p.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
        p.setVisible(true);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonSesion;
    private javax.swing.JButton botonSocios;
    private javax.swing.JDesktopPane escritorio;
    private javax.swing.Box.Filler filler1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel labelNotas;
    private javax.swing.JLabel labelSesion;
    // End of variables declaration//GEN-END:variables
}
